# <template>
  <div class="attendance-view">
    <!-- 头部 -->
    <div class="view-header">
      <div class="header-left">
        <h3>考勤记录</h3>
        <el-button link @click="$emit('close')">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <div class="header-right">
        <span class="employee-name">{{ employee.realName }}</span>
      </div>
    </div>

    <!-- 本月统计 -->
    <div class="stats-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>本月考勤统计</span>
            <span class="date">{{ currentMonth }}</span>
          </div>
        </template>
        <div class="stats-grid">
          <div class="stat-item">
            <span class="label">出勤天数</span>
            <span class="value">{{ monthStat.totalDays || 0 }}天</span>
          </div>
          <div class="stat-item">
            <span class="label">工作时长</span>
            <span class="value">{{ monthStat.totalHours || 0 }}小时</span>
          </div>
        </div>
        <div class="stats-tip">
          <span class="tip-text" style="font-size: 16px; color: #999; text-align: center; display: block;">即{{ Math.floor(monthStat.totalDays || 0) }}天零{{ Math.floor((monthStat.totalHours || 0) % 8) }}个小时</span>
        </div>
      </el-card>
    </div>

    <!-- 日历视图 -->
    <div class="calendar-section">
      <el-card>
        <template #header>
          <div class="calendar-header">
            <el-button-group>
              <el-button @click="changeMonth(-1)">
                <el-icon><ArrowLeft /></el-icon>
              </el-button>
              <el-button @click="changeMonth(1)">
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </el-button-group>
            <span class="current-month">{{ currentMonth }}</span>
          </div>
        </template>
        
        <div class="calendar">
          <!-- 星期标题 -->
          <div class="weekdays">
            <div v-for="day in ['日', '一', '二', '三', '四', '五', '六']" 
                 :key="day" 
                 class="weekday">{{ day }}</div>
          </div>
          
          <!-- 日期格子 -->
          <div class="days">
            <div v-for="(day, index) in calendarDays" 
                 :key="index"
                 class="day"
                 :class="{
                   'other-month': !day.currentMonth,
                   'has-record': day.hasRecord,
                   'today': day.isToday,
                   'type-1': day.type === 1,
                   'type-2': day.type === 2,
                   'type-3': day.type === 3
                 }"
                 @click="showDayDetail(day)">
              <span class="date">{{ day.date }}</span>
              <span v-if="day.hasRecord" class="record-type">
                {{ getTypeText(day.type) }}
              </span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 考勤记录列表 -->
    <div class="records-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>考勤记录</span>
          </div>
        </template>
        <div class="records-list">
          <div v-for="record in records" 
               :key="record.id"
               class="record-item"
               :class="'type-' + record.type">
            <div class="record-main">
              <span class="date">{{ formatDate(record.date) }}</span>
              <span class="type">{{ getFullTypeText(record.type) }}</span>
            </div>
            <div class="record-detail">
              <span class="hours">{{ record.workHours }}小时</span>
              <span v-if="record.remark" class="remark">{{ record.remark }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 日期详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="考勤详情"
      width="400px"
      destroy-on-close
    >
      <div class="detail-content" v-if="selectedDayRecord">
        <div class="detail-item">
          <span class="label">日期：</span>
          <span class="value">{{ formatFullDate(selectedDayRecord.date) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">考勤类型：</span>
          <span class="value">{{ getFullTypeText(selectedDayRecord.type) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">工作时长：</span>
          <span class="value">{{ selectedDayRecord.workHours }}小时</span>
        </div>
        <div class="detail-item" v-if="selectedDayRecord.remark">
          <span class="label">备注：</span>
          <span class="value">{{ selectedDayRecord.remark }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button type="primary" @click="handleEdit">编辑</el-button>
          <el-button type="danger" @click="handleDeleteRecord" :loading="isDeleting">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑考勤记录"
      width="400px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        v-if="showEditDialog"
      >
        <el-form-item label="考勤类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择考勤类型">
            <el-option label="全天班" :value="1" />
            <el-option label="半天班" :value="2" />
            <el-option label="小时工" :value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="工作时长" prop="workHours" v-if="editForm.type === 3">
          <el-input-number 
            v-model="editForm.workHours" 
            :min="0.5" 
            :max="24"
            :step="0.5"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="editForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit" :loading="isEditing">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Close, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getEmploeeAttentence, deleteRecord, updateRecord } from '@/api/attendance'

// Props
const props = defineProps({
  employee: {
    type: Object,
    required: true
  }
})

// Emits
const emit = defineEmits(['close'])

// 状态
const selectedDate = ref(dayjs())
const monthStat = ref({})
const records = ref([])
const selectedDayRecord = ref(null)
const showDetailDialog = ref(false)
const isDeleting = ref(false)
const showEditDialog = ref(false)
const isEditing = ref(false)
const editFormRef = ref()
const editForm = ref({
  type: 1,
  workHours: 8,
  remark: ''
})

const editRules = {
  type: [{ required: true, message: '请选择考勤类型', trigger: 'change' }],
  workHours: [
    { required: true, message: '请输入工作时长', trigger: 'blur' },
    { type: 'number', min: 0.5, max: 24, message: '工作时长必须在0.5到24小时之间', trigger: 'blur' }
  ]
}

// 计算属性
const currentMonth = computed(() => {
  return selectedDate.value.format('YYYY年MM月')
})

const calendarDays = computed(() => {
  const date = selectedDate.value
  const firstDay = date.startOf('month')
  const lastDay = date.endOf('month')
  
  // 获取日历开始日期（上月最后几天）
  const startDate = firstDay.day(0) // 从周日开始
  
  const days = []
  let currentDate = startDate
  
  // 生成6周的日历数据
  for (let i = 0; i < 42; i++) {
    const isCurrentMonth = currentDate.month() === date.month()
    const recordForDay = records.value.find(r => 
      dayjs(r.date).format('YYYY-MM-DD') === currentDate.format('YYYY-MM-DD')
    )
    
    days.push({
      date: currentDate.date(),
      currentMonth: isCurrentMonth,
      isToday: currentDate.format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD'),
      hasRecord: !!recordForDay,
      type: recordForDay?.type,
      fullDate: currentDate.format('YYYY-MM-DD'),
      record: recordForDay
    })
    
    currentDate = currentDate.add(1, 'day')
  }
  
  return days
})

// 方法
function getTypeText(type) {
  const types = {
    1: '全',
    2: '半',
    3: '时'
  }
  return types[type] || ''
}

function getFullTypeText(type) {
  const types = {
    1: '全天班',
    2: '半天班',
    3: '小时工'
  }
  return types[type] || ''
}

function formatDate(date) {
  return dayjs(date).format('MM-DD')
}

function formatFullDate(date) {
  return dayjs(date).format('YYYY年MM月DD日')
}

function changeMonth(offset) {
  selectedDate.value = selectedDate.value.add(offset, 'month')
  fetchMonthRecords()
}

// 获取本月考勤记录
async function fetchMonthRecords() {
  try {
    const startTime = selectedDate.value.startOf('month').format('YYYY-MM-DD')
    const endTime = selectedDate.value.endOf('month').format('YYYY-MM-DD')
    
    const res = await getEmploeeAttentence(
      props.employee.id,
      startTime,
      endTime
    )
    console.log(res)
    if (res && res.data) {
      records.value = res.data.records
      monthStat.value = {
        totalHours: res.data.totalHours || 0,
        totalDays: (res.data.totalHours / 8.0).toFixed(1) || 0
      }
    }
  } catch (error) {
    console.error('获取考勤记录失败:', error)
  }
}

// 显示日期详情
function showDayDetail(day) {
  if (!day.hasRecord) return
  selectedDayRecord.value = day.record
  showDetailDialog.value = true
}

// 删除考勤记录
async function handleDeleteRecord() {
  if (!selectedDayRecord.value?.id) return
  
  try {
    await ElMessageBox.confirm('确定要删除这条考勤记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    isDeleting.value = true
    const res = await deleteRecord(selectedDayRecord.value.id)
    
    if (res.code === 200) {
      ElMessage.success('删除成功')
      showDetailDialog.value = false
      // 重新获取考勤记录
      fetchMonthRecords()
    } else {
      throw new Error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  } finally {
    isDeleting.value = false
  }
}

// 打开编辑对话框
function handleEdit() {
  if (!selectedDayRecord.value) return
  
  editForm.value = {
    type: selectedDayRecord.value.type,
    workHours: selectedDayRecord.value.type === 3 ? selectedDayRecord.value.workHours : 
               selectedDayRecord.value.type === 2 ? 4 : 8,
    remark: selectedDayRecord.value.remark || ''
  }
  
  showEditDialog.value = true
}

// 保存编辑
async function handleSaveEdit() {
  if (!editFormRef.value || !selectedDayRecord.value) return
  
  try {
    await editFormRef.value.validate()
    
    isEditing.value = true
    const data = {
      date: dayjs(selectedDayRecord.value.date).format('YYYY-MM-DD'),
      type: editForm.value.type,
      workHours: editForm.value.type === 3 ? editForm.value.workHours : undefined,
      remark: editForm.value.remark
    }
    
    const res = await updateRecord(selectedDayRecord.value.id, data)
    
    if (res.code === 200) {
      ElMessage.success('修改成功')
      showEditDialog.value = false
      showDetailDialog.value = false
      // 重新获取考勤记录
      fetchMonthRecords()
    } else {
      throw new Error(res.message || '修改失败')
    }
  } catch (error) {
    if (error?.message) {
      ElMessage.error(error.message)
    }
  } finally {
    isEditing.value = false
  }
}

onMounted(() => {
  fetchMonthRecords()
})
</script>

<style scoped>
.attendance-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  overflow: auto;
}

.view-header {
  background-color: #fff;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h3 {
  margin: 0;
}

.employee-name {
  font-size: 14px;
  color: #666;
}

.stats-section,
.calendar-section,
.records-section {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
}

.stat-item .label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-item .value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.calendar {
  padding: 16px 0;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  margin-bottom: 8px;
}

.weekday {
  font-size: 14px;
  color: #666;
  padding: 8px 0;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.day {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  
  &.other-month {
    opacity: 0.3;
  }
  
  &.has-record {
    background-color: var(--el-color-primary-light-9);
    
    &.type-1 {
      background-color: var(--el-color-success-light-9);
      .date { color: var(--el-color-success); }
    }
    
    &.type-2 {
      background-color: var(--el-color-warning-light-9);
      .date { color: var(--el-color-warning); }
    }
    
    &.type-3 {
      background-color: var(--el-color-primary-light-9);
      .date { color: var(--el-color-primary); }
    }
  }
  
  &.today {
    background-color: var(--el-color-primary);
    color: #fff;
    
    .date,
    .record-type {
      color: #fff !important;
    }
  }
  
  &:hover:not(.other-month) {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.date {
  font-size: 14px;
  margin-bottom: 4px;
}

.record-type {
  font-size: 12px;
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.record-item {
  padding: 12px;
  border-radius: 4px;
  border-left: 4px solid transparent;
  
  &.type-1 {
    background-color: var(--el-color-success-light-9);
    border-left-color: var(--el-color-success);
  }
  
  &.type-2 {
    background-color: var(--el-color-warning-light-9);
    border-left-color: var(--el-color-warning);
  }
  
  &.type-3 {
    background-color: var(--el-color-info-light-9);
    border-left-color: var(--el-color-info);
  }
}

.record-main {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.record-detail {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.detail-content {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.detail-item .label {
  color: #666;
  width: 80px;
}

.detail-item .value {
  flex: 1;
  font-weight: bold;
}
</style> 